package com.weiiew.buildtypeservice.service;

import com.weiiew.common.entity.dto.BuildingType;
import com.weiiew.common.entity.vo.ItemTypeVO;
import com.weiiew.buildtypeservice.mapper.BuildingTypeMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description
 * @Author 魏锴
 * @Date 2024/8/8
 */
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class BuildingTypeServiceImpl implements BuildingTypeService {
    private final BuildingTypeMapper mapper;

    @Override
    @Cacheable(cacheNames = "build:type:list:vo", key = "#version", condition = "#name = null")
    public List<ItemTypeVO> getBuildTypes(String name, Integer version) {
        return mapper.getBuildTypes(name, version);
    }

    @Override
    @Caching(
            evict = {
                    @CacheEvict(cacheNames = "build:type:list:simple", key = "#type.version"),
                    @CacheEvict(cacheNames = "build:type:list:vo", key = "#type.version")
            }
    )
    public boolean createType(BuildingType type) {
        return mapper.insertType(type);
    }

    @Override
    @Caching(
            evict = {
                    @CacheEvict(cacheNames = "build:type:list:simple", key = "#version"),
                    @CacheEvict(cacheNames = "build:type:list:vo", key = "#version")
            }
    )
    public boolean renameType(Integer id, String name, Integer version) {
        return mapper.renameType(id, name);
    }

    @Override
    @Caching(
            evict = {
                    @CacheEvict(cacheNames = "build:type:list:simple", key = "#version"),
                    @CacheEvict(cacheNames = "build:type:list:vo", key = "#version")
            }
    )
    public boolean removeType(Integer id, Integer version) {
        if (mapper.countBuildByType(id) != 0) return false;
        return mapper.deleteType(id);
    }
}
